package net.esj.basic.utils;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.opensymphony.xwork2.ognl.OgnlUtil;

public class ImageUtils {

	/***
	 * 功能：压缩图片变成小尺寸*** 参数1：oImage：原图；* 参数2：maxWidth：小尺寸宽度；*
	 * 参数3：maxHeight：小尺寸长度；
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * @return 返回新的图片名称
	 ***/
	public static String compressImage(File oImage, int maxWidth, int maxHeight) throws FileNotFoundException, IOException {
		if(!oImage.exists()){
			return "";
		}
		String fileType = getFileType(oImage.getName());
		String newImageName =getFileNameWithoutPostfix(oImage.getName()) ;
		newImageName +="_"+maxWidth+"^"+maxHeight+"."+fileType;

		File newFile =new File(oImage.getParent()+File.separator+newImageName);
		if(newFile.exists()){
			return newFile.getName();
		}
		BufferedImage srcImage = null;
		try {
			srcImage = ImageIO.read(oImage);
		} catch (Exception e) {
			return oImage.getName();
		}
		if(srcImage==null){
			return oImage.getName();
		}
		int srcWidth = srcImage.getWidth(null);
		int srcHeight = srcImage.getHeight(null);
		if (srcWidth <= maxWidth || srcHeight <= maxHeight) {
			return oImage.getName();
		}
		if(maxWidth==0 && maxHeight>0){
			maxWidth = (int) (srcWidth/(srcHeight/maxHeight*1.0));
		}
		if(maxHeight ==0 && maxWidth>0){
			maxHeight = (int) (srcHeight/(srcWidth/maxWidth*1.0));
		}

		Image scaledImage = srcImage.getScaledInstance(srcWidth, srcHeight,
				Image.SCALE_SMOOTH);
		double ratio = Math.min((double) maxWidth / srcWidth,
				(double) maxHeight / srcHeight);
		AffineTransformOp op = new AffineTransformOp(
				AffineTransform.getScaleInstance(ratio, ratio), null);
		scaledImage = op.filter(srcImage, null);

		FileOutputStream fos =  new FileOutputStream(newFile);
		ImageIO.write((BufferedImage)scaledImage, fileType, fos);// 存盘
		fos.close();
		return newFile.getName();
	}

	/***
	 * 功能：图片加文字水印*** 参数1：oImage：原图；* 参数2：newImageName：加文字水印图片存放的路径和新名字；*
	 * 参数3：fileType：加文字水印图片类型（png,gif,jpg...）； 参数4：waterText：文字水印的内容
	 ****/
	public static boolean pressText(File oImage, String newImageName,
			String fileType, String waterText,boolean isWriteCenter) throws IOException {
		BufferedImage originalImage = ImageIO.read(oImage);
		int originalWidth = originalImage.getWidth(null);
		int originalHeight = originalImage.getHeight(null);
		if (originalWidth < 50 || originalHeight < 50) {
			return false;
		}
		if (waterText == null || waterText.trim().equals("")) {
			return false;
		}
		BufferedImage newImage = new BufferedImage(originalWidth,
				originalHeight, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = newImage.createGraphics();
		g.drawImage(originalImage, 0, 0, originalWidth, originalHeight, null);
		g.setColor(Color.RED);
		int fontSize = 13;
		g.setFont(new Font("宋体", Font.PLAIN, fontSize));
		g.setComposite(AlphaComposite
				.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
		int len = waterText.length();
		if (!isWriteCenter) {
			g.drawString(waterText, originalWidth - len * fontSize
					/ 2 - 6, originalHeight - 6);
		} else {
			g.drawString(waterText,
					(originalWidth - (len * fontSize)) / 2,
					(originalHeight - fontSize) / 2);
		}
		g.dispose();
		ImageIO.write(newImage, fileType, new FileOutputStream(newImageName));// 存盘
		return true;
	}

	/***
	 * 功能：图片加logo图片水印*** 参数1：oImage：原图；* 参数2：newImageName：加logo图片水印存放的路径和新名字；*
	 * 参数3：fileType：加logo图片水印图片类型（png,gif,jpg...）； 参数4：logoPath：logo水印图片的存放路径
	 ****/
	public static boolean pressImage(File oImage, String newImageName,
			String fileType, String logoPath,boolean isWriteCenter) throws IOException {
		File waterMarkImage = new File(logoPath);
		if (!waterMarkImage.exists()) {
			return false;
		}
		BufferedImage originalImage = ImageIO.read(oImage);
		BufferedImage watermarkImage = ImageIO.read(waterMarkImage);
		int originalWidth = originalImage.getWidth(null);
		int originalHeight = originalImage.getHeight(null);
		int watermarkWidth = watermarkImage.getWidth(null);
		int watermarkHeight = watermarkImage.getHeight(null);
		if (originalWidth <= watermarkWidth
				|| originalHeight <= watermarkHeight || originalWidth < 50
				|| originalHeight < 50) {
			return false;
		}
		BufferedImage newImage = new BufferedImage(originalWidth,
				originalHeight, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = newImage.createGraphics();
		g.drawImage(originalImage, 0, 0, originalWidth, originalHeight, null);
		g.setComposite(AlphaComposite
				.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
		if (!isWriteCenter) {
			g.drawImage(watermarkImage, originalWidth - watermarkWidth - 10,
					originalHeight - watermarkHeight - 10, watermarkWidth,
					watermarkHeight, null);
		} else {
			g.drawImage(watermarkImage, (originalWidth - watermarkWidth) / 2,
					(originalHeight - watermarkHeight) / 2, watermarkWidth,
					watermarkHeight, null);
		}
		g.dispose();
		ImageIO.write(newImage, fileType, new FileOutputStream(newImageName));// 存盘
		return true;
	}

	private static String getFileType(String filename){
		String fileType = filename.substring(filename.lastIndexOf(".")+1);
		return fileType;
	}

	private static String getFileNameWithoutPostfix(String filename){
		String newfilename = filename.substring(0,filename.lastIndexOf("."));
		return newfilename;
	}

	public static void main(String[] args) throws Exception{
		File image = new File("E:\\program\\javaws\\automat\\webapp\\melon_upload\\plugins_eav\\2013\\8\\23\\1379901310703jh89q7_1.png");
		if(image.exists()){
			compressImage(image, 0, 600);
		}else{
			throw new Exception("文件不存在");
		}
	}
}
